package com.cxs.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxs.domain.TOrder;
import com.cxs.mapper.TOrderMapper;
import com.cxs.service.TOrderService;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @Author CXS
 * @Date 2023/11/14 15:23
 **/
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    @Autowired
    private TOrderMapper orderMapper;

    /**
     * userId = 1 都会去同一个库
     * 此时只需要添加Transactional注解，就可以控制事务了
     */
    @Transactional
    @Override
    public void testTrans() {
        TOrder order = TOrder.builder()
                .orderId(1L)
                .userId(1L)
                .price(new BigDecimal(66))
                .status("1")
                .build();
        TOrder order2 = TOrder.builder()
                .orderId(2L)
                .userId(1L)
                .price(new BigDecimal(66))
                .status("1")
                .build();

        orderMapper.insert(order);
        int a = 10 / 0;
        orderMapper.insert(order2);
    }


    /**
     * userId 不相同会进入不同的库
     */
    @Override
    @Transactional // 这个必须添加
    @ShardingTransactionType(TransactionType.XA)
    public void testTrans2() {
        TOrder order = TOrder.builder()
                .orderId(1L)
                .userId(1L)
                .price(new BigDecimal(66))
                .status("1")
                .build();
        TOrder order2 = TOrder.builder()
                .orderId(2L)
                .userId(2L)
                .price(new BigDecimal(66))
                .status("1")
                .build();

        orderMapper.insert(order);
        orderMapper.insert(order2);
        int a = 10 / 0;
    }
}
